package com.shuaigef.springbootinit.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.shuaigef.springbootinit.common.BaseResponse;
import com.shuaigef.springbootinit.common.ErrorCode;
import com.shuaigef.springbootinit.common.ResultUtils;
import com.shuaigef.springbootinit.exception.BusinessException;
import com.shuaigef.springbootinit.exception.ThrowUtils;
import com.shuaigef.springbootinit.model.dto.user.UserLoginRequest;
import com.shuaigef.springbootinit.model.dto.user.UserUpdateMyRequest;
import com.shuaigef.springbootinit.model.dto.user.UserUpdateRequest;
import com.shuaigef.springbootinit.model.entity.*;
import com.shuaigef.springbootinit.model.vo.UserVO;
import com.shuaigef.springbootinit.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.shuaigef.springbootinit.common.ErrorCode.NOT_FOUND_ERROR;
import static com.shuaigef.springbootinit.common.ErrorCode.OPERATION_ERROR;
import static com.shuaigef.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private FileService fileService;
    @Resource
    private UserService userService;


    public static String extractField(String jsonString, String fieldName) {
        String regex = "(?s)\"" + fieldName + "\":\\s*\"((?:[^\"\\\\]|\\\\.)*)\"";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(jsonString);
        if (matcher.find()) {
            // 返回匹配到的内容
            return matcher.group(1);
        } else {
            // 如果没有找到匹配的内容，返回 null 或抛出异常
            return "没找到";
        }
    }

    /**
     * 批量注册
     */
    @PostMapping("/register")
    public BaseResponse<Object> register(@RequestBody HashMap<String, List<User>> map) {
        List<User> list = map.get("list");
        List<String> list1 = new ArrayList<>();
        if (list == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        for (User user : list) {
            if (user.getUserAccount().length() > 20 || user.getUserPassword().length() > 20) {
                list1.add(user.getUserAccount());
                continue;
            }
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", user.getUserAccount());
            if (userService.getOne(queryWrapper) != null || !userService.save(user)) {
                // 用户名已存在或者注册失败
                list1.add(user.getUserAccount());
            }
        }
        if (!list1.isEmpty()) {
            return ResultUtils.success(list1);
        }
        return ResultUtils.success("全部注册成功");

    }

    /**
     * 用户登录
     *
     */
    @PostMapping("/login")
    public BaseResponse<SaTokenInfo> userLogin(@RequestBody UserLoginRequest userLoginRequest) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SaTokenInfo saTokenInfo = userService.userLogin(userAccount, userPassword);
        return ResultUtils.success(saTokenInfo);
    }

    /**
     * 用户注销
     *
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout() {
        boolean result = userService.userLogout();
        return ResultUtils.success(result);
    }

    /**
     * 查看自己详情
     *
     */
    @GetMapping("/get/login")
    public BaseResponse<User> getLoginUser() {
        User user = userService.getLoginUser();
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return ResultUtils.success(user);
    }

    /**
     * 更新用户
     *
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getUserId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户
     *
     */
    @GetMapping("/get")
    // @SaCheckRole(ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     */
    @GetMapping("/get/vo")
    // @SaCheckRole(ADMIN_ROLE)
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }


    // /**
    // * 分页获取用户列表
    // *
    // */
    // @PostMapping("/list/page")
    // @SaCheckRole(ADMIN_ROLE)
    // public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest
    // userQueryRequest) {
    // long current = userQueryRequest.getCurrent();
    // long size = userQueryRequest.getPageSize();
    // Page<User> userPage = userService.page(new Page<>(current, size),
    // userService.getQueryWrapper(userQueryRequest));
    // return ResultUtils.success(userPage);
    // }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @return
     */
    // @PostMapping("/list/page/vo")
    // @SaCheckRole(ADMIN_ROLE)
    // public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody
    // UserQueryRequest userQueryRequest) {
    // if (userQueryRequest == null) {
    // throw new BusinessException(ErrorCode.PARAMS_ERROR);
    // }
    // long current = userQueryRequest.getCurrent();
    // long size = userQueryRequest.getPageSize();
    // // 限制爬虫
    // ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
    // Page<User> userPage = userService.page(new Page<>(current, size),
    // userService.getQueryWrapper(userQueryRequest));
    // Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
    // List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
    // userVOPage.setRecords(userVO);
    // return ResultUtils.success(userVOPage);
    // }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BusinessException(NOT_FOUND_ERROR);
        }
        if (userUpdateMyRequest.getUserName() != null) {
            loginUser.setUserName(userUpdateMyRequest.getUserName());
        }
        if (userUpdateMyRequest.getUserPassword() != null) {
            loginUser.setUserPassword(userUpdateMyRequest.getUserPassword());
        }
        if (userUpdateMyRequest.getUserAvatar() != null) {
            loginUser.setUserAvatar(userUpdateMyRequest.getUserAvatar());
        }
        if (userUpdateMyRequest.getUserGender() != null) {
            loginUser.setUserGender(userUpdateMyRequest.getUserGender());
        }

        // 4. 保存更新后的用户信息
        boolean result = userService.updateById(loginUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        // 5. 返回成功响应
        return ResultUtils.success(true);
    }
    /**
     * 更新用户头像
     *
     * @param
     */
    @PostMapping("/update/my/avatar")
    public BaseResponse<String> updateUserAvatar(@RequestParam("messageContent") MultipartFile file) {
        Object userObj = StpUtil.getSession().get(USER_LOGIN_STATE);
        System.err.println(userObj);
        User currentUser = (User) userObj;
        long userId = currentUser.getUserId();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserId, userId);
        String url;
        try {
            url=fileService.uploadFile(file).getData();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
        User user = new User();
        user.setUserId((int) userId);
        System.err.println(url);
        user.setUserAvatar(url);
        boolean updated = userService.update(user, queryWrapper);
        if (updated)
            return ResultUtils.success(url);
        return ResultUtils.error(OPERATION_ERROR,"上传失败");
    }

}
